#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <cstring>

using namespace std;

class Solution {
public:
    const int maxn=0x7fffffff;
    int ans=maxn,anssum;
    int min(int a,int b) {
        return (a<b) ? a:b;
    }
    int threeSumClosest(vector<int>& nums, int target) {
        int n=nums.size();
        sort(nums.begin(),nums.end());
        
        for (int i=1;i<n-1;i++) {
            for (int j=0;j<i;j++) {
                int res=target-nums[i]-nums[j];
                int from=i+1, to=n-1,k=(from+to)/2;
                while (from<to-1) {
                    k=(from+to)/2;
                    if (res-nums[k]==0) return target;
                    else if (res-nums[k]<0) {
                        to=k;
                    } else {
                        from=k; 
                    }
                }
                if (abs(res-nums[to])<abs(res-nums[from]))k=to;
                else k=from;
                if (ans>abs(res-nums[k])) {
                    ans=abs(res-nums[k]);
                    anssum=target+nums[k]- res;
                }
            }
        }
        return anssum;
    }
};

int main() {
    Solution s;
    vector<int> inp={-1,2,1,-4};
    cout<<s.threeSumClosest(inp,1);
}